import { Component } from "react";
import {
  Button,
  Cell,
  Empty,
  Avatar,
  Grid,
  Image,
  Tabs,
  Divider,
  Sticky,
} from "@nutui/nutui-react-taro";
import styles from "./index.scss";
import { useModel } from "@/store";
import Taro, { useRouter } from "@tarojs/taro";
import { useState } from "react";
import { useEffect } from "react";
import {
  queryClinicChargeItem,
  addOrder,
  getOrderList,
  queryOutpPatBill,
} from "@/services/payment";
import { useMemo } from "react";
import { queryAutoRcptNo } from "@/services/register";
import Layout from "@/components/Layout";
import NoData from "@/components/NoData";
import { formatDate, calculateTime } from "@/utils/repeated";

const buildTree = (arr, parentId = 0) => {
  const tree = [];
  for (let i = 0; i < arr.length; i++) {
    if (arr[i].parentId === parentId) {
      const children = buildTree(arr, arr[i].id);
      if (children.length) {
        arr[i].children = children;
      }
      tree.push(arr[i]);
    }
  }
  return tree;
};

export default () => {
  const { params } = useRouter();

  const { autoRcptNo } = params;
  const { user, getUser } = useModel("user");
  const { curPatientInfo } = useModel("patient");

  const [list, setList] = useState([]);

  useEffect(() => {
    queryOutpPatBill({
      // patientId: curPatientInfo.patientId,
      regSerialNo: autoRcptNo,
      // patientId: "01733667",
      // 010624031314322314 010624031314322314
      //   queryNo: curPatientInfo.patientId,
      startDate: "1970-01-01",
      endDate: calculateTime(0),
      pageSize: 999,
      pageNo: 1,
    }).then((res) => {
      console.log(res, "===");
      setList(res);
      // if(!res){

      // }

      // setList(groupedArr);
    });
  }, []);

  const [groupedArr, totalCosts] =
    useMemo(() => {
      let total = 0;

      if (!list) {
        return [[], 0];
      }

      const arr =
        list?.reduce((acc, obj) => {
          let ind = acc.findIndex(
            (x) => x.classOnOutpRcpt === obj.classOnOutpRcpt
          );

          if (ind === -1) {
            acc.push({
              classOnOutpRcpt: obj.classOnOutpRcpt,
              classOnOutRcptName: obj.classOnOutpRcptName,
              price: obj.charges,
              children: [obj],
            });
          } else {
            acc[ind].price += obj.charges;

            acc[ind].children.push(obj);
          }
          total += obj.charges;
          return acc;
        }, []) || [];

      return [arr, total];
    }, [list]) || [];

  return (
    <Layout title="缴费明细">
      <view className={styles.paymentDetailWarp}>
        <view className={styles.content}>
          <view style={{ marginTop: "20px" }}>
            就诊人：{curPatientInfo?.patientName}
          </view>
          {!list && <NoData msg="暂无付款记录" />}
          <view className={styles.paymentDetaillist}>
            {groupedArr.map((item, ind) => {
              return (
                <view className={styles.paymentCard} key={ind}>
                  <view className={styles.title1}>
                    {item.classOnOutRcptName}{" "}
                    <view className={styles.price}>
                      {item.price?.toFixed(2)}元
                    </view>
                    <Divider style={{ "--nutui-divider-margin": "6px 0" }} />
                  </view>
                  <view className={styles.detilWarp}>
                    {item.children?.map((x, ind2) => {
                      return (
                        <view
                          key={`detail-${ind2}`}
                          className={styles.detilContent}
                        >
                          <view className={styles.title2}>
                            {x.itemName}
                            <view style={{ marginTop: "10rpx" }}>
                              数量：{x.amount || 1}
                              {x.units || ""} 单价{" "}
                              <view className={styles.price}>
                                {/* { x.unitPrice}元 */}

                                {(
                                  Math.round(
                                    (x.unitPrice  || 0) * 100
                                  ) / 100
                                )?.toFixed(2)}
                              </view>
                            </view>
                          </view>
                        </view>
                      );
                    })}
                  </view>
                </view>
              );
            })}
          </view>
        </view>

        <view className={styles.footer}>
          <view className={styles.totalPrice}>
            总计：
            <view className={styles.price}>{totalCosts.toFixed(2)}元</view>
          </view>
          {/* <view className={styles.payBtn} onClick={onPay}>
          立即支付
        </view> */}
        </view>
      </view>
    </Layout>
  );
};
